//
//  EnumViewController.swift
//  EasyDana
//
//  Created by mac on 2024/10/16.
//

import UIKit
import RxSwift
import RxCocoa
class EnumViewController: UIViewController {

    var name: String = ""
    
    var source: [AuthenItemModel.ItemEnumModel] = []
    
    @IBOutlet weak var nameLabel: UILabel!
    
    @IBOutlet weak var tableView: UITableView!
    
    private let bag = DisposeBag()
    
    let currentModel = BehaviorRelay<AuthenItemModel.ItemEnumModel?>.init(value: nil)
    
    let confirm = PublishSubject<AuthenItemModel.ItemEnumModel?>()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configView()
        // Do any additional setup after loading the view.
    }
    @IBAction func closeAction(_ sender: Any) {
        self.dismiss(animated: false)
    }
    
    @IBAction func confirmAction(_ sender: Any) {
        self.confirm.onNext(self.currentModel.value)
        self.dismiss(animated: false)
    }
    
    private func configView() {
        self.nameLabel.text = self.name
        self.tableView.register(UINib(nibName: "EnumTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "EnumTableViewCell")
        self.tableView.separatorStyle = .none
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.showsVerticalScrollIndicator = false
        self.currentModel
            .subscribe(onNext: { [weak self] model in
                self!.tableView.reloadData()
            })
            .disposed(by: self.bag)
    }
}

extension EnumViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.source.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "EnumTableViewCell") as! EnumTableViewCell
        let model = self.source[indexPath.row]
        cell.model = model
        cell.choosed = self.currentModel.value?.cordially == model.cordially
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.source[indexPath.row]
        self.currentModel.accept(model)
    }
}
